//
//  RTOAuthViewController.swift
//  Weibo
//
//  Created by Brisinga on 16/3/5.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_APPKEY = "931880914"
let WB_REDIRECT_URI = "http://www.itheima.com/" // 授权回调页面
let WB_APPSECRET = "80328e91fb58750daa48b8f12a243b4f"

class RTOAuthViewController: UIViewController {
    
    // 懒加载OAuthLoginUrl
    
    private lazy var OAuthLoginUrl = NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)")!
    
    
    // 重写loadView
    override func loadView() {
        
        view = webView
    }
    
    override func viewDidLoad() {
        
        // 初始化内部组件
        setupUI()
        
        
    }
    
    
    
    private func setupUI() {
        
        navigationItem.title = "新浪微博"
        
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "backAction")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
    
    }
    
    
    
    // 返回App
    @objc private func backAction() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    // 自动填充用户信息
    @objc private func autoFill() {
    
        print("自动填充信息")
        
        let jsString = "document.getElementById('userId').value='vgfjh15964@163.com';document.getElementById('passwd').value='qw1987'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    // 懒加载webView
    private lazy var webView: UIWebView = {
    
        let webView = UIWebView()
        
        webView.delegate = self
        
        let request = NSURLRequest(URL: self.OAuthLoginUrl)
        
        webView .loadRequest(request)
        
        return webView
        
    }()
}



extension RTOAuthViewController: UIWebViewDelegate {
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("\(request.URL)")
        
        // 判断url是否为空
        guard let url = request.URL else {
        
            return true
        }
        
        let urlString = url.absoluteString
        
        // 判断是否已http://www.itheima.com/开头
        if urlString.hasPrefix(WB_REDIRECT_URI) {
            
            let query = url.query!
            
            // 截取授权码
            let code = query.substringFromIndex("code=".endIndex)
            
            print(code)
            
            // 创建userAcountViewModel 单例
            let userAcountViewModel = RTUserAcountViewModel.sharedAccountViewModel
            
            userAcountViewModel.loadAccessToken(code, callBack: { (isSuccess) -> () in
                
                if isSuccess {
                
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        
                        print("登录成功")
                        
                        // 发送通知切换跟控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(RTSwitchRootVCNotification, object: self)
                    })
                    
                    
                }else {
                
                    // 提示请求失败
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
            
            return false
            
        }
        
            return true
        
    }
    
    
    
   }
